package org.phytodata.actionengine;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.pentaho.platform.api.engine.IPluginManager;
import org.pentaho.platform.engine.core.system.PentahoSystem;

public class ActionFactory {
  
  private static final Log log = LogFactory.getLog(ActionFactory.class);

  private Map<String, Class<?>> actionByNameMap = new HashMap<String, Class<?>>();

  public ActionFactory() {
    ActionEngine engine = new ActionEngine();
    List<ActionInfo> actionInfos = engine.getActionInfos();
    Class<?> actionClass = null;
    for (ActionInfo info : actionInfos) {
      try {
        if (info.getPlugin().equals("[NATIVE]")) {
          actionClass = Class.forName(info.getClassName());
        } else {
          IPluginManager pluginManager = PentahoSystem.get(IPluginManager.class);
          actionClass = pluginManager.loadClass(info.getName());
        }
      } catch (Exception e) {
        log.error("Could not load action "+info.getName(), e);
      }
      actionByNameMap.put(info.getName(), actionClass);
    }
  }

  public Object create(String actionName) throws InstantiationException, IllegalAccessException {
    return actionByNameMap.get(actionName).newInstance();
  }

}
